9551. Sum a * a + … + b * b
Given two positive integers a and b, find the
sum of the squares of all numbers from a to b, i.e., a2 + (a + 1)2 +
... + b2.
Input. Two
positive integers a and b (1 ≤ a ≤ b ≤ 1000).
Output. Print the
value of the specified sum.
Sample
input |
Sample
output |
3 7 |
135 |
loops
Algorithm analysis
Compute the specified sum using
a loop.
Read the input data.
scanf("%d %d", &a, &b);
The variable s is used to compute the sum a * a + ...
+ b * b with a for loop.
Before starting the loop, the variable s is initialized to 0.
s = 0;
for (i = a; i <= b; i++)
s = s + i * i;
Print the answer.
printf("%lld\n", s);
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int a = con.nextInt();
int b = con.nextInt();
int sum = 0;
for (int i = a; i <= b; i++)
sum = sum + i * i;
System.out.println(sum);
con.close();
}
}
Read the input data.
a, b = map(int,input().split())
The variable s is used to compute the sum a * a + ...
+ b * b with a for loop.
Before starting the loop, the variable s is initialized to 0.
s = 0
for i in range(a, b + 1):
s = s + i * i
Print the answer.
print(s)